<template>
  <a-flex :gap="8">
    <div>
      <!-- 发送按钮 -->
      <a-button type="primary" @click="sendMessage" :style="{ marginBottom: '16px' }">
        发送消息
      </a-button>
      <!-- 消息气泡 -->
      <Bubble v-if="content" :content="content" />
    </div>
    <div>
      <ThoughtChain :items="thoughtItems" />
    </div>
  </a-flex>
</template>

<script setup name="BubbleStreamProtocol">
import { TagsOutlined } from '@ant-design/icons-vue'
import { Bubble, ThoughtChain, XStream } from 'ant-design-x-vue'
import { computed, ref } from 'vue'
import tool from '@/utils/tool'
import sysConfig from '@/config/index'


const lines = ref([])
const content = computed(() => {
  try {
    return lines.value.map((line) => {
      // 尝试解析JSON数据
      try {
        const data = JSON.parse(line.data)
        return data.content || ''
      } catch {
        // 如果解析失败，直接返回原始数据
        return line.data
      }
    }).join('')
  } catch (error) {
    console.error('Error parsing content:', error)
    return ''
  }
})

async function sendMessage() {
  // 清空之前的消息
  lines.value = []
  
  try {
    const token = tool.data.get('TOKEN')
    // 创建SSE连接
    const response = await fetch(`http://127.0.0.1:82/ai/chat/send`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'text/event-stream',
        'token': sysConfig.TOKEN_PREFIX + token
      },
      body: JSON.stringify({
        message: '你好',
        sessionId: '1' // 这里可以根据需要设置会话ID
      }),
    })

    // 读取SSE数据流
    for await (const chunk of XStream({
      readableStream: response.body,
    })) {
      console.log(chunk)
      lines.value = [...lines.value, chunk]
    }
  } catch (error) {
    console.error('Error:', error)
  }
}

const thoughtItems = computed(() => {
  if (!lines.value.length) return []
  
  return [{
    title: '对话记录',
    status: 'success',
    icon: h(TagsOutlined),
    content: h('pre', { style: { overflow: 'scroll' } }, [
      ...lines.value.map(i => h('code', { key: i.data }, i.data))
    ])
  }]
})
</script>

<style scoped>
pre {
  width: auto;
  margin: 0;
}

pre code {
  display: block;
  padding: 12px 16px;
  font-size: 14px;
}
</style>